<?php

namespace app\admin\validate;

use think\Validate;
use think\Db;

class Ocation extends Validate
{

    /**
     * 验证规则
     */
    protected $rule = [
        'name' => 'require|checkOcationName',
    ];

    /**
     * 检查教学点名称是否重复
     * 在同一父级下，教学点名称不能重复
     */
    protected function checkOcationName($value, $rule, $data)
    {
        if (empty($value)) {
            return '教学点名称不能为空';
        }

        // 检查名称长度
        if (mb_strlen($value, 'utf-8') < 2 || mb_strlen($value, 'utf-8') > 1000) {
            return '教学点名称长度必须在2-1000个字符之间';
        }

        $pid = isset($data['pid']) ? $data['pid'] : 0;
        $id = isset($data['id']) ? $data['id'] : 0;

        // 构建查询条件
        $where = [
            'name' => $value,
            'pid' => $pid,
            'status' => ['neq', -1] // 排除已删除的记录
        ];

        // 如果是编辑操作，排除当前记录
        if ($id > 0) {
            $where['id'] = ['neq', $id];
        }

        $count = Db::name('ocation')->where($where)->count();

        if ($count > 0) {
            return '在当前父级下已存在同名的教学点，请更换名称';
        }

        return true;
    }

    protected function checkDistrictId($value, $rule, $data)
    {
        if ($data['city_id']== '0') {
            return true;
        }
        if($value==""||$value=="-1"){
            return false;
        }
        return true;
    }

    /**
     * 提示消息
     */
    protected $message = [
        'name.require' => '教学点名称不能为空',
        'name.checkOcationName' => '教学点名称验证失败',
        'city_id.require' => '请选择城市',
        'address.require' => '请填写地址'
    ];

    /**
     * 字段描述
     */
    protected $field = [
        'name' => '教学点名称',
        'city_id' => '城市',
        'district_id' => '区县',
        'address' => '地址'
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'add' => [
            'name' => 'require|checkOcationName',
            'city_id' => 'require',
            'district_id' => 'checkDistrictId',
            'address' => 'require',
        ],
        'edit' => [
            'name' => 'require|checkOcationName',
            'city_id' => 'require',
            'district_id' => 'checkDistrictId',
            //'address' => 'require',
        ]
    ];

    public function __construct(array $rules = [], $message = [], $field = [])
    {
        $this->field = [
            'name' => "教学点名称",
        ];
        $this->message = array_merge($this->message, [
            'name.regex' => '学校名称长度出错',
        ]);
        parent::__construct($rules, $message, $field);
    }

}
